<template>
  <div class="div-view-search">
    <el-row gutter="20" class="search">
      <el-col :span="4">
        <el-select v-model="selectedType" placeholder="选择验证状态" @change="handleFilterChange" class="filter-select">
          <el-option label="所有状态" value=""></el-option>
          <el-option label="已通过" value="0"></el-option>
          <el-option label="待审核" value="1"></el-option>
          <el-option label="未通过" value="2"></el-option>
        </el-select>
      </el-col>
      <el-col id="btn0" :span="3">
        <el-button type="primary" @click="dialogVisible = true">添加旅行社信息</el-button>
      </el-col>
      <el-col :offset="11" :span="4">
        <el-input v-model="searchName" placeholder="请输入旅行社名称" />
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-col>
    </el-row>
  </div>
  <div class="div-view">
    <!-- 表格 -->
    <div class="table">
      <el-table :data="sortedAgencies" :header-cell-style="{ backgroundColor: '#f0f0f0' }" style="width: 100%"
        @sort-change="handleSortChange">
        <el-table-column property='agencyId' label="旅行社ID" />
        <el-table-column property="userId" label="关联用户ID" />
        <el-table-column property="agencyName" label="名称" />
        <!-- 修改资质证明文件列 -->
        <el-table-column label="资质证明文件">
          <template #default="scope">
              <!-- 判断是否有 PDF 链接 -->
              <a v-if="scope.row.agencyQualification"
                 @click.prevent="handleDownloadPDF(scope.row.agencyId)"
                 href="#">
                  下载资质证明
              </a>
              <span v-else>暂无资质证明</span>
          </template>
      </el-table-column>
        <el-table-column property="applyingTime" label="申请时间" sortable="custom" />
        <el-table-column property="qualifyStatus" label="验证状态">
          <template #default="scope">
            <span class="status-container">
              <el-icon size="20">
                <CircleCheck :class="getStatusIconClass(scope.row.qualifyStatus)" />
              </el-icon>
              <span>{{ getStatusText(scope.row.qualifyStatus) }}</span>
            </span>
          </template>
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column width="250" label="操作">
          <template #default="{ row }">
            <!-- 驳回申请按钮，仅当状态为1（待审核）时可点击 -->
            <el-button type="danger" @click="handleRejectApplication(row)" :disabled="row.qualifyStatus !== 1" link>
              驳回申请
            </el-button>
            <!-- 取消资格按钮，仅当状态为0（已通过）时可点击 -->
            <el-button type="primary" @click="handleCancelQualification(row)" :disabled="row.qualifyStatus !== 0" link>
              取消资格
            </el-button>
            <!-- 通过审核按钮，仅当状态为1（待审核）时可点击 -->
            <el-button type="success" @click="handleApproveApplication(row)" :disabled="row.qualifyStatus !== 1" link>
              通过审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:currentPage="pageNum" v-model:pageSize="pageSize" :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="display: flex; justify-content: flex-end; margin-top: 10px;" />
    </div>
  </div>
  <div>
    <canvas id="mChart" style="width: 600px; height: 400px;"></canvas>
  </div>
  <!-- 弹窗 -->
  <el-dialog v-model="dialogVisible" title="旅行社表单" width="500" :before-close="handleClose">
    <template #footer>
      <div class="dialog-footer">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
          class="demo-ruleForm" :size="formSize" status-icon>
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="ruleForm.userId" />
          </el-form-item>
          <el-form-item label="旅行社名称" prop="agencyName">
            <el-input v-model="ruleForm.agencyName" />
          </el-form-item>
          <el-form-item label="旅行社资质" prop="agencyQualification">
            <el-input v-model="ruleForm.agencyQualification" />
          </el-form-item>
          <el-form-item label="验证状态" prop="qualifyStatus">
            <el-select v-model="ruleForm.qualifyStatus" placeholder="Select status">
              <el-option label="已通过" value="0" />
              <el-option label="待审核" value="1" />
              <el-option label="未通过" value="2" />
            </el-select>
          </el-form-item>
          <div style="display: flex; justify-content: flex-end;">
            <el-form-item>
              <el-button type="primary" @click="handleSubmit">提交</el-button>
              <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, reactive } from 'vue';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';


// 定义接口类型
interface RuleForm {
  userId: number;
  agencyName: string;
  agencyQualification: string;
  // applyingTime: string;
  qualifyStatus: number;
}

// 响应式数据
const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  userId: 0,
  agencyName: '',
  agencyQualification: '',
  qualifyStatus: 0,
});

// 表单校验规则
const rules = reactive<FormRules<RuleForm>>({
  agencyName: [{ required: true, message: '请输入旅行社名称', trigger: 'blur' }],
  agencyQualification: [{ required: true, message: '请输入旅行社资质', trigger: 'blur' }],
  qualifyStatus: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
});

// 显示模态框
const dialogVisible = ref(false);

// 提交表单
const handleSubmit = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.post('http://localhost:8088/agencies/add', ruleForm);
        console.log('提交成功:', response.data);
        getData();
        ElMessage({ message: '添加成功', type: 'success' });
        dialogVisible.value = false;
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage({ message: '提交失败,请输入正确的userid', type: 'error' });
      }
    } else {
      console.log('表单校验失败!');
    }
  });
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};


// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(0);
const searchName = ref('');
//定义数据数组
const tableData = ref([]);

// 定义选中的下拉框值
const selectedType = ref('');

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭弹窗吗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
// 获取数据的函数
const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:8088/agencies/filter', {
      params: {
        qualifyStatus: selectedType.value,
      },
    });
    tableData.value = response.data.agencies;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// 下载 PDF 方法
const handleDownloadPDF = async (designerId) => {
    try {
        console.log(`开始请求签名 URL，designerId: ${designerId}`);

        // 请求后端接口获取签名 URL
        const response = await axios.get(`/getQualificationPath`, {
            params: { designerId, timestamp: new Date().getTime() }, // 加入时间戳确保每次请求都是新请求
        });

        console.log(`签名 URL 请求成功，返回数据:`, response.data);

        const signedUrl = response.data;  // 获取签名 URL
        console.log(`签名 URL：`, signedUrl);

        if (!signedUrl) {
            throw new Error("未能获得有效的签名 URL");
        }

        // 使用签名 URL 触发文件下载
        const a = document.createElement('a');
        a.href = signedUrl;
        a.download = 'qualification1.pdf';  // 可以指定下载的文件名
        document.body.appendChild(a);
        a.click();  // 触发下载
        document.body.removeChild(a);
        console.log("下载请求已发出");

    } catch (error) {
        console.error("下载失败：", error);
        ElMessage.error("文件下载失败，请稍后重试！");
    }
};

// 处理下拉框变化的函数
const handleFilterChange = () => {
  fetchData();
};

const getData = async () => {
  try {
    const response = await axios.get('http://localhost:8088/agencies/getByPage', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
      },
    });
    tableData.value = response.data.records;
    total.value = response.data.total;
    pageNum.value = response.data.current;
    pageSize.value = response.data.size;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};
// 当前页或每页数量改变时重新获取数据
const handleSizeChange = () => {
  getData();
};
const handleCurrentChange = () => {
  getData();
};

const handleSearch = async () => {
  try {
    const response = await axios.get('http://localhost:8088/agencies/getByName', { params: { agencyName: searchName.value } });
    tableData.value = response.data;
  } catch (error) {
    console.error('查找出错:', error);
  }
};

// 更新操作的函数
const updateAgencyStatus = async (agencyId, qualifyStatus) => {
  try {
    // 构建包含ID和新状态的请求体
    const requestBody = {
      agencyId,
      qualifyStatus,
    };

    const response = await axios.put(
      "http://localhost:8088/agencies/update",
      requestBody
    );

    if (response.data) {
      ElMessage.success("操作成功");
      // 同步更新表格中的数据状态
      const agency = tableData.value.find((item) => item.agencyId === agencyId);
      if (agency) {
        agency.qualifyStatus = qualifyStatus;
      }
    }
    return response.data;
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新失败");
    return null;
  }
};

// 0已通过 1待审核 2未通过
// 驳回申请 1-->2
// 通过申请 1-->0
// 取消资格 0-->2
// 驳回申请
const handleRejectApplication = (row) => {
  updateAgencyStatus(row.agencyId, 2); // 改为状态2表示驳回
};

// 取消资格
const handleCancelQualification = (row) => {
  updateAgencyStatus(row.agencyId, 2); // 改为状态2表示取消资格
};

// 通过审核
const handleApproveApplication = (row) => {
  updateAgencyStatus(row.agencyId, 0); // 改为状态0表示通过审核
};

// 组件挂载后获取初始数据
onMounted(() => {
  fetchData();
  getData();
});


// 当前排序的属性和顺序
const sortProp = ref('');
const sortOrder = ref(''); // 'ascending' 或 'descending'
const sortedAgencies = computed(() => {
  return tableData.value.slice().sort((a, b) => {
    if (sortProp.value === 'applyingTime') {
      const timeA = new Date(a.applyingTime).getTime();
      const timeB = new Date(b.applyingTime).getTime();
      return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA;
    }
    return 0;
  });
});

// 处理排序变化的函数
const handleSortChange = (newSortInfo) => {
  sortProp.value = newSortInfo.prop;
  sortOrder.value = newSortInfo.order;
};
//处理状态栏样式
function getStatusIconClass(qualifyStatus) {
  switch (qualifyStatus) {
    case 0:
      return 'status-icon-green';
    case 1:
      return 'status-icon-red';
    case 2:
      return 'status-icon-gray';
  }
}
function getStatusText(qualifyStatus) {
  switch (qualifyStatus) {
    case 0:
      return '已通过';
    case 1:
      return '待审核';
    case 2:
      return '未通过';
  }
}

const handleEdit = (row) => {
  // 编辑操作的逻辑
  console.log('Editing row:', row);
};
const handleDelete = (row) => {
  // 删除操作的逻辑
  console.log('Deleting row:', row);
};



</script>

<style scoped>
.div-view {
  background-color: #fff;
  padding: 10px 10px;
  /* 内边距 */
  border-radius: 5px;
  /* 圆角 */
  margin-bottom: 10px;
  /* 下边距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 阴影 */
}

.div-view-search {
  background-color: #fff;
  padding: 10px 10px;
  /* 内边距 */
  border-radius: 5px;
  /* 圆角 */
  margin-bottom: 10px;
  /* 下边距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 阴影 */
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 图标特定类，仅用于图标 */
.status-icon-green {
  color: green;
  margin-right: 5px;
  /* 图标和文本之间的间距 */
}

.status-icon-red {
  color: red;
  margin-right: 5px;
}

.status-icon-gray {
  margin-right: 5px;
  color: gray;
}
</style>